<template>
	<!-- 头部搜索条件 -->
	<a-card :bordered="false" class="mb-3">
		<!-- <a-breadcrumb separator=">" class="mb-4 pl-[10px]">
			<a-breadcrumb-item>合同管理</a-breadcrumb-item>
			<a-breadcrumb-item><a href="">合同管理</a></a-breadcrumb-item>
		</a-breadcrumb> -->
		<div class="flex justify-between items-center">
			<a-space :size="16">
				<a-input-group compact>
					<a-select v-model:value="searchType" style="width: 150px" @change="searchText = ''">
						<a-select-option :value="0">合同编号</a-select-option>
						<a-select-option :value="1">甲方抬头</a-select-option>
						<a-select-option :value="2">甲方联系人/法人</a-select-option>
						<a-select-option :value="3">甲方联系电话</a-select-option>
						<a-select-option :value="4">转换后甲方抬头</a-select-option>
					</a-select>
					<a-input
						v-model:value="searchTextComputed"
						style="width: 200px"
						placeholder="请输入关键字搜索"
						@pressEnter="table.clearRefreshSelected(true)"
					></a-input>
				</a-input-group>
				<a-input-group compact>
					<a-select
						placeholder="请选择"
						v-model:value="searchOption.userType"
						class="w-[100px]"
						:options="[
							{ label: '创建人', value: 0 },
							{ label: '转换人', value: 1 }
						]"
						:filter-option="false"
					></a-select>
					<a-select
						placeholder="请选择"
						v-model:value="searchOption.userVal"
						class="w-[200px]"
						:options="userList"
						:filter-option="false"
						allowClear
						showSearch
						@search="searchCreater"
						@change="changeCreater"
					></a-select>
				</a-input-group>
				<a-button type="primary" @click="table.refresh(true)">查询</a-button>
				<a-button @click="screenVisible = true">更多筛选</a-button>
			</a-space>
			<a-button v-if="hasPerm('bizContractSwitchExport')" :loading="loading" type="primary" @click="onExportContract"
				>导出</a-button
			>
		</div>
	</a-card>
	<!-- 表格展示区域 -->
	<!--	class="h-full"-->
	<a-card :bordered="false">
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:page-num="pageNum"
			:size="pageSize"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:scroll="{ x: 1200 }"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'code'">
					<a v-if="hasPerm('bizContractSwitchView')" @click="onDetail(record.id)">{{ record.code }}</a>
					<span v-else>{{ record.code }}</span>
				</template>
				<template v-if="column.dataIndex === 'balancePayment'">
					<span>{{ record.paymentMethod === 'FULL' ? '-' : record.balancePayment ?? '-' }}</span>
				</template>
				<template v-if="column.dataIndex === 'depositAmount'">
					<span>{{ record.paymentMethod === 'FULL' ? '-' : record.depositAmount ?? '-' }}</span>
				</template>
				<template v-if="column.dataIndex === 'contractStatus'">
					<span>{{ statusEnum[record.contractStatus] }}</span>
				</template>
				<template v-if="column.dataIndex === 'signPayment'">
					<span>{{ signPayEnum[record.signPayment] }}</span>
				</template>
				<template v-if="column.dataIndex === 'paymentMethod'">
					<span>{{ payMethodEnum[record.paymentMethod] }}</span>
				</template>
				<template v-if="column.dataIndex === 'approvalStatus'">
					<span>{{ approvalStatusEnum[record.approvalStatus] }}</span>
				</template>
				<template v-if="column.dataIndex === 'financeApprovalStatus'">
					<span>{{ approvalStatusEnum[record.financeApprovalStatus] }}</span>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-popover placement="left">
						<template #content>
							<div class="flex flex-col">
								<a-button v-if="hasPerm('bizContractSwitchView')" type="link" @click="onDetail(record.id)">
									查看详情
								</a-button>
							</div>
						</template>
						<a>操作</a>
					</a-popover>
				</template>
			</template>
		</s-table>
	</a-card>
	<!-- 更多筛选条件 -->
	<a-modal
		v-model:visible="screenVisible"
		title="更多筛选"
		:footer="null"
		:closable="false"
		:width="500"
		@cancel="cancelMoreSearch"
	>
		<a-form :label-col="labelCol">
			<a-form-item label="转换类型">
				<a-select
					v-model:value="moreSearch.isTotal"
					:options="transTypeOptions.slice(1)"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="签约方式">
				<a-select
					v-model:value="moreSearch.signMethod"
					:options="signMethodOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="签约场景">
				<a-select
					v-model:value="moreSearch.signPayment"
					:options="signPayOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="付款类型">
				<a-select
					v-model:value="moreSearch.paymentMethod"
					:options="payMethodOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="合同金额">
				<a-input-group compact>
					<a-select style="width: 30%" v-model:value="moreSearch.comparisonOperators" placeholder="请选择">
						<a-select-option value="gt">></a-select-option>
						<a-select-option value="eq">=</a-select-option>
						<a-select-option value="lt">&lt;</a-select-option>
					</a-select>
					<a-input-number style="width: 70%" v-model:value="moreSearch.contractAmount" placeholder="请输入" />
				</a-input-group>
			</a-form-item>
			<a-form-item label="服务类目">
				<a-cascader
					v-model:value="moreSearch.serviceCategoryId"
					:options="categorySearchs"
					allowClear
					placeholder="请选择"
				></a-cascader>
			</a-form-item>
			<a-form-item label="签约日期">
				<a-range-picker
					class="w-full"
					valueFormat="YYYY-MM-DD"
					v-model:value="moreSearch.signingDate"
					:placeholder="['请选择', '请选择']"
				/>
			</a-form-item>
			<a-form-item label="合同模板">
				<a-select
					v-model:value="moreSearch.templateId"
					:options="templateOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="转换时间">
				<a-range-picker
					class="w-full"
					valueFormat="YYYY-MM-DD"
					v-model:value="moreSearch.transTime"
					:placeholder="['请选择', '请选择']"
				/>
			</a-form-item>
		</a-form>
		<div class="flex justify-between items-center mt-[40px]">
			<a-button type="link" @click="clearSearch">清空筛选</a-button>
			<a-space>
				<a-button type="primary" @click="doMoreSearch">筛选</a-button>
				<a-button @click="cancelMoreSearch">取消</a-button>
			</a-space>
		</div>
	</a-modal>
</template>
<script setup>
	import contractApi from '@/api/biz/bizContractApi'
	import erpApi from '@/api/biz/bizCommonApi'
	import tool from '@/utils/tool'
	import {
		signPayEnum,
		payMethodEnum,
		statusEnum,
		approvalStatusEnum,
		signMethodOptions,
		signMethodEnum,
		transTypeOptions,
		transTypeEnum
	} from '../contractManagement/enum/contractEnum'
	import downloadUtil from '@/utils/downloadUtil'
	import { useRouter } from 'vue-router'
	import useTableCache from '@/hook/useTableCache'

	const router = useRouter()
	const tableCache = useTableCache('contractSwitch', ['bizContractSwitch', 'bizContractSwitchDetail'])

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	onBeforeMount(() => {
		const tableCacheData = tableCache.get()
		if (tableCacheData) {
			searchType.value = tableCacheData.searchType
			searchText.value = tableCacheData.searchText
			searchOption.value = tableCacheData.searchOption
			moreSearch.value = tableCacheData.moreSearch
			pageNum.value = tableCacheData.pageNum
			pageSize.value = tableCacheData.pageSize
		}

		getCategorys()
		getTemplates()
		getCreaters()
	})
	const columns = [
		{
			title: '合同编号',
			dataIndex: 'code',
			width: 200,
			align: 'center',
			fixed: 'left'
		},
		{
			title: '合同模板',
			dataIndex: 'templateName',
			width: 200,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '甲方抬头',
			dataIndex: 'firstParty',
			width: 260,
			align: 'center',
			ellipsis: true
		},
		{
			title: '转换后甲方抬头',
			dataIndex: 'transCustomerName',
			width: 260,
			align: 'center',
			ellipsis: true
		},
		{
			title: '乙方抬头',
			dataIndex: 'secondPartyName',
			width: 260,
			align: 'center',
			ellipsis: true
		},
		{
			title: '转换类型',
			dataIndex: 'isTotal',
			width: 120,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => transTypeEnum[text] || '-'
		},
		{
			title: '签约方式',
			dataIndex: 'signMethod',
			width: 100,
			align: 'center',
			customRender: ({ text }) => signMethodEnum[text] || '-'
		},
		{
			title: '签约场景',
			dataIndex: 'signPayment',
			width: 150,
			align: 'center'
		},
		{
			title: '付款类型',
			dataIndex: 'paymentMethod',
			width: 100,
			align: 'center'
		},
		{
			title: '合同总金额',
			dataIndex: 'contractAmount',
			width: 120,
			align: 'center'
		},
		{
			title: '定金总金额',
			dataIndex: 'depositAmount',
			width: 120,
			align: 'center'
		},
		{
			title: '合同抵扣金额',
			dataIndex: 'transContractAmount',
			width: 120,
			align: 'center'
		},
		{
			title: '合同转换时间',
			dataIndex: 'transTime',
			width: 150,
			align: 'center'
		},
		{
			title: '合同转换人',
			dataIndex: 'transUserName',
			width: 120,
			align: 'center',
			ellipsis: true
		},
		{
			title: '合同创建时间',
			dataIndex: 'createAt',
			width: 150,
			align: 'center'
		},
		{
			title: '合同创建人',
			dataIndex: 'createUserName',
			width: 120,
			align: 'center',
			ellipsis: true
		}
	]
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		fixed: 'right',
		width: '100px'
	})
	/**
	 * 获取所有服务类目
	 */
	const categorySearchs = ref([])
	const getCategorys = () => {
		erpApi.getCategory().then((res) => {
			categorySearchs.value = res
		})
	}
	/**
	 * 合同模板
	 */
	const templateOptions = ref([])
	const getTemplates = () => {
		contractApi.getBusinessTemplateList({}).then((res) => {
			templateOptions.value = res.map((item) => {
				return {
					label: item.templateName,
					value: item.templateId
				}
			})
		})
	}

	const searchType = ref(0)
	const searchText = ref('')
	const searchTextComputed = computed({
		get() {
			return searchText.value
		},
		set(val) {
			searchText.value = val.replace(/(^\s*)|(\s*$)/g, '')
		}
	})
	const searchOption = ref({
		code: undefined,
		firstParty: undefined,
		firstPartyPerson: undefined,
		firstPartyMobile: undefined,
		transCustomerName: undefined,
		userType: 0,
		userVal: undefined,
		createUser: undefined,
		transUser: undefined
	})
	/**
	 * 获取业务员搜索
	 */
	const userList = ref([])
	const searchKey = ref('')
	const saveUserList = ref([])
	const getCreaters = () => {
		const params = {
			searchKey: searchKey.value
		}
		contractApi.authUserSelector(params).then((res) => {
			userList.value = res.map((item) => {
				return {
					label: item.name,
					value: `${item.id}`
				}
			})
			saveUserList.value = JSON.parse(JSON.stringify(userList.value))
		})
	}
	let timeout
	const searchCreater = (value) => {
		if (timeout) {
			clearTimeout(timeout)
			timeout = null
		}
		userList.value = saveUserList.value.filter((v) => {
			return v.label.indexOf(value) !== -1
		})
	}
	const changeCreater = (value) => {
		if (!value) {
			userList.value = JSON.parse(JSON.stringify(saveUserList.value))
		}
	}

	// 签约场景
	const signPayOptions = tool.dictList('SignPayment')
	// 收款方式
	const payMethodOptions = tool.dictList('PAYMENT_METHOD')

	/**
	 * 更多筛选条件逻辑
	 */
	const screenVisible = ref(false)
	const labelCol = { style: { width: '100px' } }
	// 更多筛选条件初始值
	const moreDefaultSearch = {
		isTotal: null,
		signMethod: null,
		signPayment: null,
		paymentMethod: null,
		contractAmount: null,
		serviceCategoryId: null,
		signingDate: null,
		templateId: null,
		transTime: null
	}
	const moreSearch = ref({ ...moreDefaultSearch })
	const clearSearch = () => {
		moreSearch.value = { ...moreDefaultSearch }
	}
	const doMoreSearch = () => {
		screenVisible.value = false
		table.value.refresh(true)
	}
	const cancelMoreSearch = () => {
		screenVisible.value = false
	}
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const table = ref(null)
	const pageNum = ref(1)
	const pageSize = ref(10)

	/**
	 * 公共查询参数
	 */
	const getParams = (parameter = {}) => {
		if (searchType.value === 0) {
			searchOption.value.code = searchText.value
			searchOption.value.firstParty = null
			searchOption.value.firstPartyPerson = null
			searchOption.value.firstPartyMobile = null
			searchOption.value.transCustomerName = null
		} else if (searchType.value === 1) {
			searchOption.value.code = null
			searchOption.value.firstParty = searchText.value
			searchOption.value.firstPartyPerson = null
			searchOption.value.firstPartyMobile = null
			searchOption.value.transCustomerName = null
		} else if (searchType.value === 2) {
			searchOption.value.code = null
			searchOption.value.firstParty = null
			searchOption.value.firstPartyPerson = searchText.value
			searchOption.value.firstPartyMobile = null
			searchOption.value.transCustomerName = null
		} else if (searchType.value === 3) {
			searchOption.value.code = null
			searchOption.value.firstParty = null
			searchOption.value.firstPartyPerson = null
			searchOption.value.firstPartyMobile = searchText.value
			searchOption.value.transCustomerName = null
		} else if (searchType.value === 4) {
			searchOption.value.code = null
			searchOption.value.firstParty = null
			searchOption.value.firstPartyPerson = null
			searchOption.value.firstPartyMobile = null
			searchOption.value.transCustomerName = searchText.value
		}

		if (searchOption.value.userType === 0) {
			searchOption.value.createUser = searchOption.value.userVal
			searchOption.value.transUser = null
		} else if (searchOption.value.userType === 1) {
			searchOption.value.createUser = null
			searchOption.value.transUser = searchOption.value.userVal
		}

		const params = {
			...searchOption.value,
			...moreSearch.value,
			...parameter,
			type: '1'
		}
		if (params.serviceCategoryId) {
			params.serviceCategoryId = params.serviceCategoryId.join(',')
		}
		if (params.signingDate) {
			params.startSigningDate = params.signingDate[0]
			params.endSigningDate = params.signingDate[1]
			delete params.signingDate
		}
		if (params.transTime) {
			params.startTransTime = params.transTime[0]
			params.endTransTime = params.transTime[1]
			delete params.transTime
		}

		return params
	}

	/**
	 * 获取合同列表数据
	 */
	const loadData = (parameter) => {
		const params = getParams(parameter)
		return contractApi.getContractList(params).then((res) => {
			return res
		})
	}

	/**
	 * 导出合同
	 */
	const loading = ref(false)
	const onExportContract = () => {
		loading.value = true
		const params = getParams()
		contractApi
			.exportList(params)
			.then((res) => {
				downloadUtil.resultDownload(res)
			})
			.finally(() => {
				loading.value = false
			})
	}

	/**
	 * 详情
	 */
	const onDetail = (id) => {
		tool.limitClick(() => {
			const { localPagination } = table.value
			tableCache.set({
				searchType: searchType.value,
				searchText: searchText.value,
				searchOption: searchOption.value,
				moreSearch: moreSearch.value,
				pageNum: localPagination.current,
				pageSize: localPagination.pageSize
			})
			router.push(`/biz/contractSwitch/detail/${id}`)
		})
	}
</script>
<style lang="less" scoped>
	:deep(.ant-table-thead > tr > th::before) {
		width: 0 !important;
	}
	.center {
		text-align: center;
	}
	// :deep(.ant-table) {
	// 	min-height: calc(100vh - 350px);
	// }
</style>
